package com.jf3q.front.controller;

import com.alipay.api.domain.OrderDetail;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jf3q.common.domain.EduCourse;
import com.jf3q.common.domain.EduMember;
import com.jf3q.common.domain.EduTeacher;
import com.jf3q.common.service.EduCourseService;
import com.jf3q.common.service.TeacherService;
import com.jf3q.common.utils.JwtTokenUtil;
import com.jf3q.common.vo.ResultVo;
import com.jf3q.common.domain.Order;
import com.jf3q.front.dto.OrderDto;
import com.jf3q.common.service.OrderService;
import com.jf3q.front.service.MemberService;
import com.jf3q.front.service.TradeService;
import com.jf3q.front.vo.PayVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@RestController
@RequestMapping("/order")
@Tag(name = "订单")
public class OrderController {
    @Autowired
    EduCourseService courseService;
    @Autowired
    MemberService memberService;
    @Autowired
    OrderService orderService;
    @Autowired
    TeacherService teacherService;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    private TradeService tradeService;

    //创建支付二维码
    @GetMapping("/qrcode/{orderId}")
    @Operation(summary = "支付二维码")
    public ResultVo getQrCode(@PathVariable String orderId){
        Order order = orderService.getById(orderId);
        String path = tradeService.tradeQrCode(order);
        if (StringUtils.isNotEmpty(path)){
            PayVo payVo = new PayVo();
            payVo.setOid(order.getId());
            payVo.setTotalFee(order.getTotalFee());
            payVo.setPath(path);
            payVo.setCourseId(order.getCourseId());
            return ResultVo.success(payVo);
        }
        return ResultVo.error("创建失败");
    }
    @GetMapping("/queryOrderStatus/{orderSn}")
    @Operation(summary = "查询订单状态")
    public ResultVo queryOrderStatus(@PathVariable String orderSn){
        Boolean result = tradeService.alipayTradeQuery(orderSn);
        if (result){
            return ResultVo.success(result);
        }else {
            return ResultVo.error(25000,"");
        }
    }
    @GetMapping("/createOrder/{courseId}")
    @Operation(summary = "生成订单")
    public ResultVo createOrder(@PathVariable String courseId, HttpServletRequest request) {
        try {
            Order order = new Order();
            EduCourse course = courseService.getById(courseId);
            UUID uuid = new UUID(System.currentTimeMillis(), 20);
            order.setOrderNo(uuid.randomUUID().toString().replaceAll("-", "").substring(12));
            order.setCourseId(course.getId());
            order.setCourseTitle(course.getTitle());
            order.setCourseCover(course.getCover());
            LambdaQueryWrapper<EduTeacher> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(EduTeacher::getId,course.getTeacherId());
            EduTeacher teacher = teacherService.getOne(queryWrapper1);
            order.setTeacherName(teacher.getName());
            String token = request.getHeader("token");
            String userName = jwtTokenUtil.getUserNameFromToken(token);
            LambdaQueryWrapper<EduMember> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(EduMember::getMobile,userName);
            EduMember member = memberService.getOne(queryWrapper);
            order.setMemberId(member.getId());
            order.setNickname(member.getNickname());
            order.setMobile(member.getMobile());
            order.setTotalFee(course.getPrice());
            order.setStatus(0);
            order.setIsDeleted(0);
            orderService.save(order);
            return ResultVo.success(order.getId());
        } catch (Exception e) {
            return ResultVo.error("生成订单失败");
        }
    }

    @GetMapping("/getOrderInfo/{orderId}")
    @Operation(summary = "查看订单")
    public ResultVo getOrderInfo(@PathVariable String orderId) {
        Order order = orderService.getById(orderId);
        return ResultVo.success(order);
    }

    @PostMapping("/getOrderList")
    @Operation(summary = "查看个人订单")
    //tradeState 订货状态 courseTitle课程标题 memberId 会员id  ASC 表示升序（默认值），或者使用 DESC 表示降序
    public ResultVo getOrderList(@RequestBody OrderDto orderDto) {
        Page<Order> page = new Page<>(orderDto.getPageNum(), orderDto.getPageSize());
        Page<Order> orderPage = orderService.getOrderList(
                orderDto.getMemberId(),
                orderDto.getTradeState(),
                orderDto.getCourseTitle(),
                orderDto.getOrderBy(),
                page
        );
        return ResultVo.success("订单查询", orderPage);
    }

    @GetMapping("/{orderId}")
    @Operation(summary = "订单详情")
    public ResultVo getOrder(@PathVariable String orderId) {
        Order order = orderService.getOrder(orderId);
        return ResultVo.success("订单详情", order);
    }

    @DeleteMapping("/{orderId}")
    @Operation(summary = "删除订单")
    public ResultVo delOrder(@PathVariable String orderId){

        if (orderService.removeById(orderId)) {
            return ResultVo.success("删除订单成功",null);
        }
        return ResultVo.success(" 删除订单失败",null);

    }
}
